package com.kgc.javaweb.servlet;

import cn.hutool.captcha.LineCaptcha;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.kgc.javaweb.dto.UserPageDTO;
import com.kgc.javaweb.entity.*;
import com.kgc.javaweb.enums.CodeMsg;
import com.kgc.javaweb.service.CarChargeService;
import com.kgc.javaweb.service.OwnerService;
import com.kgc.javaweb.service.UserService;
import com.kgc.javaweb.service.impl.CarChargeServiceImpl;
import com.kgc.javaweb.service.impl.OwnerServiceImpl;
import com.kgc.javaweb.service.impl.UserServiceImpl;
import com.kgc.javaweb.util.JsonResultWriter;
import com.kgc.javaweb.util.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    private OwnerService ownerService=new OwnerServiceImpl();

    CarChargeService carChargeService = new CarChargeServiceImpl();


    // 获取验证码
    protected void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LineCaptcha lineCaptcha = new LineCaptcha(140, 50, 4, 5);
        String code = lineCaptcha.getCode();
        req.getSession().setAttribute("code", code);

        ServletOutputStream outputStream = resp.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();

    }

    //登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取前端页面中发送的数据
        String username = req.getParameter("username");
        System.out.println("username = " + username);
        String password = req.getParameter("password");
        System.out.println("password = " + password);
        String captcha = req.getParameter("captcha");
        System.out.println("captcha = " + captcha);

        Integer type = Integer.valueOf(req.getParameter("type"));

        // 判定验证码是否正确

        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");

        //创建一个响应结果对象
        ResponseResult responseResult = new ResponseResult();

        if (code.equals(captcha)) {
            // 登录请求的验证
            //判断用户类型
            if (type==1)//管理员
            {
                try {
                    UserInfo userinfo = userService.login(username, password);

                    if (userinfo!= null) {
                        responseResult.setMsg(CodeMsg.LOGIN_SUCCESS.getMsg());
                        responseResult.setCode(CodeMsg.LOGIN_SUCCESS.getCode());
                        // 将登录成功的用户信息存入 session 用于后续的非法请求的验证
                        req.getSession().setAttribute("userinfo", userinfo);
                        JsonResultWriter.writerJson(resp, responseResult);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (type==0)
            {
                try {
                    Owner owner = ownerService.ownerLogin(username, password);
                    if (owner!= null) {
                        responseResult.setMsg(CodeMsg.LOGIN_SUCCESS.getMsg());
                        responseResult.setCode(CodeMsg.LOGIN_SUCCESS.getCode());
                        // 将登录成功的用户信息存入 session 用于后续的非法请求的验证
                        req.getSession().setAttribute("owner", owner);
                        JsonResultWriter.writerJson(resp, responseResult);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }

        responseResult.setMsg(CodeMsg.LOGIN_FAIL.getMsg());
        responseResult.setCode(CodeMsg.LOGIN_FAIL.getCode());
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //注册查询用户名是否存在
    protected void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        System.out.println("username = " + username);

        //  调用用户的业务层进行用户名的校验
        Boolean b = userService.checkUserName(username);
        //  根据查询的结果 响应数据给前端浏览器     html  json   {code:200,msg:"ok",data:user}
        ResponseResult responseResult = ResponseResult.builder().build();
        if (!b) {
            responseResult.setCode(200);
            responseResult.setMsg("用户名可用");
        } else {
            responseResult.setCode(500);
            responseResult.setMsg("用户名不可用");
        }
        // 通过工具类作出响应
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //注册账号
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取前端页面中发送的数据
        String username = req.getParameter("username");
        System.out.println("username = " + username);
        String password = req.getParameter("password");
        System.out.println("password = " + password);
        String captcha = req.getParameter("captcha");
        System.out.println("captcha = " + captcha);

        // 判定验证码是否正确

        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");

        //创建一个响应结果对象
        ResponseResult responseResult = new ResponseResult();

        if (code.equals(captcha)) {
            // 登录请求的验证
            //判断用户类型

            try {
                userService.register(username, password);
                responseResult.setMsg(CodeMsg.REGISTER_SUCCESS.getMsg());
                responseResult.setCode(CodeMsg.REGISTER_SUCCESS.getCode());
                JsonResultWriter.writerJson(resp, responseResult);
                return;

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        responseResult.setMsg(CodeMsg.REGISTER_FAIL.getMsg());
        responseResult.setCode(CodeMsg.REGISTER_FAIL.getCode());
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //退出登录
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ResponseResult responseResult = ResponseResult.builder().build();
        try {
            req.getSession().invalidate();
            responseResult.setMsg("退出登录,页面即将跳转");
            responseResult.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setMsg("退出失败");
            responseResult.setCode(500);
        }
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //管理员信息回显
    protected void selectUserInfoById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String id = req.getParameter("id");
        System.out.println("id = " + id);

        ResponseResult responseResult = userService.selectById(id);
        JsonResultWriter.writerJson(resp, responseResult);
    }

    //修改管理员信息
    protected void updateUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        // json 字符串
        String user = req.getParameter("userinfo");
        UserInfo userInfo = JSONUtil.toBean(user, UserInfo.class);
        System.out.println("userInfo = " + userInfo);

        ResponseResult responseResult = userService.update(userInfo);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //修改管理员密码
    protected void updateUserInfoPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        // 获取相关参数
        String oldPassword = req.getParameter("old_password");
        String newPassword = req.getParameter("new_password");

        // 判定用户的旧密码是否正确
        HttpSession session = req.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("userinfo");
        String password = userInfo.getPassword();

        System.out.println("password = " + password);
        ResponseResult responseResult = new ResponseResult().builder().build();

        if(password.equals(oldPassword)){
            // 调用业务层  更新用户密码
            responseResult =  userService.updateUserInfoPwdById(newPassword,userInfo.getId());
        }else {
            responseResult.setMsg("原始密码不正确");
            responseResult.setCode(500);
        }
        JsonResultWriter.writerJson(resp, responseResult);
    }






//========================================================================
    //童辉
//========================================================================


    //车位费查询
    protected void selectPageCarInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer limit = Integer.valueOf(req.getParameter("limit"));
        Integer page = Integer.valueOf(req.getParameter("page"));
        String searchParams = req.getParameter("searchParams");
        JSONObject jsonObject = JSONUtil.parseObj(searchParams);
        String status = String.valueOf(jsonObject.get("status"));
        if (("2").equals(status)){
            status = null;
            System.out.println("ssss = " + status);
            UserPageDTO userPageDTO = UserPageDTO.builder().page(page).limit(limit).searchParams(status).build();
            ResponseResult responseResult = carChargeService.selectPage(userPageDTO);
            System.out.println("responseResult = " + responseResult);
            JsonResultWriter.writerJson(resp, responseResult);
        }
        UserPageDTO userPageDTO = UserPageDTO.builder().page(page).limit(limit).searchParams(searchParams).build();
        ResponseResult responseResult = carChargeService.selectPage(userPageDTO);
        System.out.println("responseResult = " + responseResult);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //删除
    protected void deleteCarInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ids = req.getParameter("ids");
        System.out.println("id = " + ids);
        ResponseResult responseResult = carChargeService.delete(ids);
        JsonResultWriter.writerJson(resp,responseResult);
    }

    //添加
    protected void addCarInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = req.getParameter("user");
        CarChargeInfo carChargeInfo = JSONUtil.toBean(user, CarChargeInfo.class);
        ResponseResult responseResult = carChargeService.add(carChargeInfo);
        JsonResultWriter.writerJson(resp,responseResult);
    }

    //修改
    protected void updateCarInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = req.getParameter("user");
        System.out.println("user = " + user);
        CarChargeInfo carChargeInfo = JSONUtil.toBean(user, CarChargeInfo.class);
        System.out.println("carChargeInfo = " + carChargeInfo);
        ResponseResult responseResult = carChargeService.update(carChargeInfo);
        JsonResultWriter.writerJson(resp,responseResult);
    }

    //回显
    protected void selectParkById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        ResponseResult responseResult = carChargeService.selectAdminById(id);
        JsonResultWriter.writerJson(resp, responseResult);
    }


//========================================================================
    //姜智博
//========================================================================


    //用户管理
    // 用户信息分页查询  查询所有用户信息分页    搜索用户信息分页
    protected void selectUserPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer page = Integer.valueOf(req.getParameter("page"));
        Integer limit = Integer.valueOf(req.getParameter("limit"));
        String searchParams = req.getParameter("searchParams");
        System.out.println(searchParams);

        UserPageDTO userPageDTO = UserPageDTO.builder().limit(limit).page(page).searchParams(searchParams).build();
        ResponseResult responseResult = userService.selectUserPage(userPageDTO);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 根据id 查询用户信息
    protected void selecUsertById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        ResponseResult responseResult = userService.selectUserById(id);
        JsonResultWriter.writerJson(resp, responseResult);

    }


    // 修改用户信息
    protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // json 字符串
        String user = req.getParameter("user");
        User usr = JSONUtil.toBean(user, User.class);
        System.out.println("usr = " + usr);

        ResponseResult responseResult = userService.updateUser(usr);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 添加用户信息
    protected void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String user = req.getParameter("user");
        User usr = JSONUtil.toBean(user, User.class);
        System.out.println("usr = " + usr);
        ResponseResult responseResult = userService.addUser(usr);
        JsonResultWriter.writerJson(resp, responseResult);
    }

    // 删除用户信息
    protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String ids = req.getParameter("ids");

        ResponseResult responseResult =  userService.deleteUser(ids);
        JsonResultWriter.writerJson(resp, responseResult);

    }



//========================================================================
// 姚俊涛
//========================================================================

    // 分页查询-员工信息
    protected void selectAdminPage1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer page = Integer.valueOf(req.getParameter("page"));
        Integer limit = Integer.valueOf(req.getParameter("limit"));
        String searchParams = req.getParameter("searchParams");
        System.out.println(searchParams);


        UserPageDTO userPageDTO = UserPageDTO.builder().limit(limit).page(page).searchParams(searchParams).build();
        ResponseResult responseResult = userService.selectAdminPage1(userPageDTO);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 分页查询-公告
    protected void selectAdminPage2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer page = Integer.valueOf(req.getParameter("page"));
        Integer limit = Integer.valueOf(req.getParameter("limit"));
        String searchParams = req.getParameter("searchParams");
        System.out.println(searchParams);


        UserPageDTO userPageDTO = UserPageDTO.builder().limit(limit).page(page).searchParams(searchParams).build();
        ResponseResult responseResult = userService.selectAdminPage2(userPageDTO);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    //分页查询-维修

    //公告-开关状态
    protected void state(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        ResponseResult responseResult = new ResponseResult();

        boolean checked = Boolean.parseBoolean(req.getParameter("checked"));
        Integer id = Integer.valueOf(req.getParameter("id"));
        System.out.println(id);

        System.out.println(checked);
        userService.state(checked,id);

    }

    // 根据id 查询用户信息   回显
    protected void selectAdminById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        ResponseResult responseResult = userService.selectAdminById(id);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 修改用户信息
    protected void updateAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // json 字符串
        String notic = req.getParameter("notice");
        Notice notice = JSONUtil.toBean(notic, Notice.class);
        System.out.println(notice);

        ResponseResult responseResult = userService.updateAdmin(notice);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 添加用户信息
    protected void addAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String notic = req.getParameter("notice");
        Notice notice = JSONUtil.toBean(notic, Notice.class);

        ResponseResult responseResult = userService.addAdmin(notice);
        JsonResultWriter.writerJson(resp, responseResult);
    }

    // 删除用户信息
    protected void deleteAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String ids = req.getParameter("ids");

        ResponseResult responseResult =  userService.deleteAdmin(ids);
        JsonResultWriter.writerJson(resp, responseResult);


    }

    //修改密码
    protected void changeAdminPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        // 获取相关参数  old_password  new_password  again_password
        String oldPassword = req.getParameter("old_password");
        String newPassword = req.getParameter("new_password");

        // 判定用户的旧密码是否正确
        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("user");
        String password = admin.getPassword();

        ResponseResult responseResult = new ResponseResult().builder().build();

        if(password.equals(SecureUtil.md5(oldPassword))){
            // 调用业务层  更新用户密码
            responseResult =  userService.updateAdminPwdById(newPassword,admin.getId());
        }else {
            responseResult.setMsg("原始密码不正确");
            responseResult.setCode(500);
        }
        JsonResultWriter.writerJson(resp, responseResult);
    }






//========================================================================
//========================================================================

    //业主登录信息回显
    protected void selectOwnerById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String id = req.getParameter("id");
        System.out.println("id = " + id);

        ResponseResult responseResult=ownerService.selectOwnerById(id);

        JsonResultWriter.writerJson(resp, responseResult);


    }

    //业主信息修改
    protected void OwnerUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");


        String own = req.getParameter("owner");
        Owner owner = JSONUtil.toBean(own,Owner.class);

        System.out.println("owner = " + owner);

        ResponseResult responseResult = ownerService.update(owner);
        JsonResultWriter.writerJson(resp, responseResult);


    }

    //业主报修
    protected void ownerRepairType(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String address = req.getParameter("address");
        String name = req.getParameter("name");

        ResponseResult responseResult =ownerService.repair(name,address);
        JsonResultWriter.writerJson(resp, responseResult);


    }

    //修改用户密码
    protected void updateOwnerPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        // 获取相关参数
        String oldPassword = req.getParameter("old_password");
        String newPassword = req.getParameter("new_password");

        // 判定用户的旧密码是否正确
        HttpSession session = req.getSession();
        Owner owner = (Owner) session.getAttribute("owner");
        String password = owner.getPassword();

        System.out.println("password = " + password);
        ResponseResult responseResult = new ResponseResult().builder().build();

        if(password.equals(oldPassword)){
            // 调用业务层  更新用户密码
            responseResult =  ownerService.updateUserInfoPwdById(newPassword,owner.getId());
        }else {
            responseResult.setMsg("原始密码不正确");
            responseResult.setCode(500);
        }
        JsonResultWriter.writerJson(resp, responseResult);
    }


}
